package com.per.hjh.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.per.hjh.controller.base.BaseSpringCcontroller;
import com.per.hjh.model.User;
import com.per.hjh.service.UserService;
import com.per.other.until.ImageCode;
import com.per.other.until.UserHelper;





@Controller
public class MainController extends BaseSpringCcontroller  {
public MainController() {
	// TODO Auto-generated constructor stub
}
@Autowired
	private UserService userService;
@Autowired
private ImageCode imageCode;
private static String sRand;
public void setUserService(UserService userService) {
	this.userService = userService;
}
	@RequestMapping(value="/userLogin")
	public ModelAndView userLogin(HttpServletRequest request,HttpServletResponse response,User user){
	String sessioncode=request.getParameter("code");
	HttpSession httpSession=request.getSession();
	String session= (String) httpSession.getAttribute(imageCode.getSessionKey());
	ModelAndView result;
	if(session==null||!session.equalsIgnoreCase(sessioncode)){
		System.out.println("===="+session);
		result=new ModelAndView("redirect:/login.do");
		result.addObject("tip","验证码错误");
		return result;
		
	}else{
		
		if(UserHelper.login(user, request)){
			result=new ModelAndView("redirect:/index.do");
			return result;
		}
		else {
			result=new ModelAndView("redirect:/login.do");
			result.addObject("tip","密码错误");
			return result;
		}
	}
		
	}
	@RequestMapping("/login")
	public ModelAndView getIndex(){	
		return new ModelAndView("/login");
	}
	@RequestMapping(value = "/getImage")
    public void getImage(HttpServletRequest request, HttpServletResponse response
            ) throws IOException {
        // 禁止图片缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        // 将图像输出到servlet输出流中
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(imageCode.getImage(request), "jpeg", sos);
        sos.close();
        sRand=(String)request.getAttribute("sRand");
        String result="ok";
    
    }
}
